#!/usr/bin/python
# coding=utf-8

# 20180804
# author：葛木瓜
# 从西安房管局意向登记平台爬取已完成的登记信息
# 长安区登记平台
# http://124.115.228.93/zfrgdjpt/xmgsca.aspx
# 非长安区登记平台
# http://124.115.228.93/zfrgdjpt/xmgs.aspx

from selenium import webdriver
from PIL import Image
import time
import os


class GetCurRegis:
    """
    获取当前登记的项目情况
    包括：项目名、申请总数、刚需家庭、刚需家庭、
    """
    def __init__(self, url):

        self.url = url
        # self.driver = webdriver.Firefox()
        # self.driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])
        self.driver = webdriver.PhantomJS(executable_path='D:\\Python36\\phantomjs.exe')
        self.driver.get(url)
        self.driver.implicitly_wait(5)

    def get_cur_regis_data(self):
        """
        获取项目当前登记的情况
        :return:
        """
        cur_xm_dict = {}
        driver = self.driver
        regis_lst = driver.find_elements_by_xpath('.//*[@class="xmgsItem"]/div[1]/div[1]/span[1]')
        for regis_lst_i in range(len(regis_lst)):
            cur_xm_lst = []
            driver.switch_to.default_content()
            xm_name = regis_lst[regis_lst_i].text
            driver.execute_script("arguments[0].scrollIntoView();", regis_lst[regis_lst_i])
            sale_announce_lst = driver.find_elements_by_xpath('//*/span[text()="登记情况"]')
            sale_announce_lst[regis_lst_i].click()
            driver.switch_to.frame('layui-layer-iframe%d' % (regis_lst_i + 1))
            time.sleep(2)
            cur_xm_lst.append(driver.find_element_by_css_selector('#highcharts-0 > svg > g:nth-child(11) > g > text').text)
            cur_xm_lst.append(driver.find_element_by_css_selector('#highcharts-0 > svg > g:nth-child(12) > g > text').text)
            cur_xm_lst.append(driver.find_element_by_css_selector('#highcharts-0 > svg > g:nth-child(13) > g > text').text)
            cur_xm_dict[xm_name] = cur_xm_lst
            # 登记情况截图
            try:
                now = time.strftime('%Y-%m-%d %H_%M_%S')
                driver.save_screenshot('page.png')
                # 获取iframe_size
                iframe = driver.find_element_by_id('form1')
                iframe_half = (iframe.size['width']//2, iframe.size['height']//2)
                img = Image.open('./page.png')
                # 获取截图中点，中点坐标 ±（边长/2）= 右下角坐标/左上角坐标
                midpoint = (img.size[0] // 2, img.size[1] // 2)
                img = img.crop((midpoint[0]-iframe_half[0], midpoint[1]-iframe_half[1], midpoint[0]+iframe_half[0], midpoint[1]+iframe_half[1]))  # 截取验证码图片
                img.save('./img/' + now + '_ScreenShot.png')
                os.remove('./page.png')
            except Exception as e:
                print(e)
            driver.find_element_by_xpath('//*/span[text()="关闭"]').click()

        driver.quit()

        return cur_xm_dict


if __name__ == '__main__':
    url = 'http://124.115.228.93/zfrgdjpt/xmgsca.aspx?state=1'
    s = GetCurRegis(url).get_cur_regis_data()
    print(s)
